package com.warframe.sortie;

import com.alibaba.fastjson.JSON;
import com.tools.HibernateUtils;
import com.tools.StringContent;
import com.warframe.entity.database.WikiTranslateEO;
import com.warframe.entity.market.warframe.WarframeMarketMO;
import com.warframe.entity.message.Message;
import com.warframe.entity.sortie.SortieMO;
import com.warframe.entity.sortie.VariantsMO;
import com.warframe.message.Executor;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Sortie implements Runnable {

    private static String url = "https://api.warframestat.us/pc/sortie";
    private static String wikitranslateSqlForSorties = "select * from WikiTranslate a where a.item_en in (TARGET) order by a.item_cn";
    private Message message;
    private List<VariantsMO> variantsMOList;
    private List<String> stringList;

    public Sortie(Message message) {
        this.message = message;
        variantsMOList = new ArrayList<>();
        stringList = new ArrayList<>();
    }

    private void getResult() {
        CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建httpClient实例
        HttpGet httpGet = new HttpGet(url); // 创建httpget实例
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        CloseableHttpResponse response = null; // 执行http get请求
        try {
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity(); // 获取返回实体
        String res = null;
        try {
            res = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SortieMO sortieMO = JSON.parseObject(res, SortieMO.class);
        variantsMOList = sortieMO.getVariants();
        for (VariantsMO eachMO : variantsMOList) {
            StringBuilder sortieStr = new StringBuilder("任务类型 : ");
            sortieStr.append(eachMO.getMissionType() + "\n");
            sortieStr.append("任务节点 : ");
            sortieStr.append(eachMO.getNode() + "\n");
            sortieStr.append(eachMO.getModifier());
            stringList.add(sortieStr.toString());
        }
    }

    private void explainModifier() {
        List<String> params = new ArrayList<>();
        for (VariantsMO eachMO : variantsMOList) {
            params.addAll(Arrays.asList(eachMO.getModifier().split(": ")));
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String eachStr : params) {
            stringBuilder.append("'" + eachStr + "'");
        }
        String result = stringBuilder.toString();
        result = result.replace("''", "','");
        Session session = HibernateUtils.getSessionFactory().openSession();
        SQLQuery sqlQuery = session.createSQLQuery(wikitranslateSqlForSorties.replace("TARGET", result));
        List<WikiTranslateEO> wikiTranslateEOList = sqlQuery.addEntity(WikiTranslateEO.class).list();
        Collections.sort(wikiTranslateEOList,this::compareDesc);
        List<String> resultList = new ArrayList<>();
        for (String str : stringList) {
            for (WikiTranslateEO eachEO : wikiTranslateEOList) {
                str = str.replace(eachEO.getItemEn(), eachEO.getItemCn());
            }
            resultList.add(str);
        }
        stringList = resultList;
        session.close();
    }

    private int compareDesc(WikiTranslateEO o1, WikiTranslateEO o2) {
        if (o1.getItemEn().length() > o2.getItemEn().length()) {
            return -1;
        } else if (o1.getItemEn().length() < o2.getItemEn().length()) {
            return 1;
        }
        return 0;
    }

    private void explainType() {
        List<String> params = new ArrayList<>();
        for (VariantsMO eachMO : variantsMOList) {
            params.add(eachMO.getMissionType());
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String eachStr : params) {
            stringBuilder.append("'" + eachStr + "'");
        }
        String result = stringBuilder.toString();
        result = result.replace("''", "','");
        Session session = HibernateUtils.getSessionFactory().openSession();
        SQLQuery sqlQuery = session.createSQLQuery(wikitranslateSqlForSorties.replace("TARGET", result));
        List<WikiTranslateEO> wikiTranslateEOList = sqlQuery.addEntity(WikiTranslateEO.class).list();
        List<String> resultList = new ArrayList<>();
        for (String str : stringList) {
            for (WikiTranslateEO eachEO : wikiTranslateEOList) {
                str = str.replace(eachEO.getItemEn(), eachEO.getItemCn());
            }
            resultList.add(str);
        }
        stringList = resultList;
        session.close();
    }

    private void explainNode() {
        List<String> params = new ArrayList<>();
        for (VariantsMO eachMO : variantsMOList) {
            String str = eachMO.getNode();
            params.add(str.substring(str.indexOf("(") + 1, str.lastIndexOf(")")));
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String eachStr : params) {
            stringBuilder.append("'" + eachStr + "'");
        }
        String result = stringBuilder.toString();
        result = result.replace("''", "','");
        Session session = HibernateUtils.getSessionFactory().openSession();
        SQLQuery sqlQuery = session.createSQLQuery(wikitranslateSqlForSorties.replace("TARGET", result));
        List<WikiTranslateEO> wikiTranslateEOList = sqlQuery.addEntity(WikiTranslateEO.class).list();
        List<String> resultList = new ArrayList<>();
        for (String str : stringList) {
            for (WikiTranslateEO eachEO : wikiTranslateEOList) {
                str = str.replace(eachEO.getItemEn(), eachEO.getItemCn());
            }
            resultList.add(str);
        }
        stringList = resultList;
        session.close();
    }

    @Override
    public void run() {
        if (StringContent.SORTIEINFO.isEmpty()) {
            getResult();
            explainType();
            explainNode();
            explainModifier();
            StringBuilder sorite = new StringBuilder();
            for (String str : stringList) {
                sorite.append(str + "\n");
            }
            StringContent.SORTIEINFO.put("Sortie", sorite.toString());
        }
        message.setSign(StringContent.SENDPERSON);
        message.setMsg(StringContent.SORTIEINFO.get("Sortie"));
        Executor.getInstance().pushMsg(message);
    }
}

